package com.gzyj.jtt808.v2019;

import com.gzyj.jtt808.utils.HexBytesUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.Data;

import java.io.Serializable;

/**
 * @author lhj
 */

@Data
public class PackageHeader implements Serializable {

    private int msgId;//消息ID
    private HeaderMsgBodyProperty msgBodyProperty;//消息体属性

    private byte ProtocolVersion = 1;//协议版本号(2019版本)

    private String terminalPhoneNo;//终端手机号
    private int msgNum;//消息流水号

    //消息包封装项
    private int packgeCount;//消息总包数
    private int packageIndex;//报序号 从1开始

    private static short internalMsgNo = 0;

    public PackageHeader() {
    }


    public PackageHeader(int msgId) {
        synchronized ((Short) internalMsgNo) {
            if (internalMsgNo == Short.MAX_VALUE) {
                internalMsgNo = 0;
            }
        }
        this.msgNum = ++internalMsgNo;

        this.msgId = msgId;
    }

    public ByteBuf encode() {
        int size = 17;
        if (this.msgBodyProperty.isSubcontract()) {
            size = 21;
        }

        ByteBuf buf = Unpooled.buffer(size);

        buf.writeShort(this.msgId);
        buf.writeBytes(this.msgBodyProperty.encode());
        if (this.msgBodyProperty.isVersionFlag()) {
            //2019版
            buf.writeByte(this.ProtocolVersion);
            buf.writeBytes(HexBytesUtil.WriteBCD(this.terminalPhoneNo, 20));

        } else {
            buf.writeBytes(HexBytesUtil.WriteBCD(this.terminalPhoneNo, 12));
        }


        buf.writeShort(this.msgNum);
        if (this.msgBodyProperty.isSubcontract()) {
            buf.writeShort(this.packgeCount);
            buf.writeShort(this.packageIndex);
        }

        return buf;

    }

    public PackageHeader decode(ByteBuf buf) {
        this.msgId = buf.readUnsignedShort();
        byte[] temp = HexBytesUtil.readByOffset(buf, 2);
        this.msgBodyProperty = new HeaderMsgBodyProperty();
        this.msgBodyProperty.decode(temp);

        if (this.msgBodyProperty.isVersionFlag()) {
            //2019 版
            this.ProtocolVersion = buf.readByte();

            temp = HexBytesUtil.readByOffset(buf, 10);
            this.terminalPhoneNo = HexBytesUtil.ReadBCD(temp, 20);
        } else {
            temp = HexBytesUtil.readByOffset(buf, 6);
            this.terminalPhoneNo = HexBytesUtil.ReadBCD(temp, 12);
        }

        this.msgNum = buf.readUnsignedShort();

        if (this.msgBodyProperty.isSubcontract()) {
            this.packgeCount = buf.readUnsignedShort();
            this.packageIndex = buf.readUnsignedShort();
        }


        return this;
    }
}
